﻿namespace HynuIOTA.Web.Areas.Admin.Controllers
{
    using HynuIOTA.Common.Attribute;
    using HynuIOTA.Entity;
    using HynuIOTA.Entity.FormatEntity;
    using HynuIOTA.Web.Helpers;
    using HynuIOTA.Web.Models;
    using System;
    using System.Data.Entity;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Web.Mvc;
    using static HynuIOTA.Common.StringConst;

    public class UserController : BaseController
    {
        /// <summary>
        /// GET: Admin/User/UserList
        /// 用户列表页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult UserList()
        {
            return View();
        }

        /// <summary>
        /// GET: Admin/User/AddUser
        /// 添加用户页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddUser()
        {
            return View();
        }

        /// <summary>
        /// GET: Admin/User/EditUser
        /// 编辑用户页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> EditUser(int? Id)
        {
            if (Id == null)
            {
                return OpContext.JsonMsgFail(MODEL_VALIDATECODE_ERROR);
            }

            var user = await OpContext.Service.User.Where(u => u.Id == Id.Value).FirstOrDefaultAsync();
            if (user == null)
            {
                return OpContext.JsonMsgFail(DATA_NOEXIST_ERROR);
            }

            ViewBag.user = user;
            return View();
        }

        /// <summary>
        /// POST: Admin/User/PostUser
        /// 添加用户
        /// </summary>
        /// <param name="postUserViewModel"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxRequest]
        public async Task<ActionResult> PostUser(PostUserViewModel postUserViewModel)
        {
            if (ModelState.IsValid == false)
            {
                return OpContext.JsonMsgFail(MODEL_VALIDATECODE_ERROR);
            }

            if (await OpContext.Service.User.Where(u => u.UserName == postUserViewModel.UserName).AnyAsync() == true)
            {
                return OpContext.JsonMsgFail(USER_USERNAMEEXIST_ERROR);
            }

            var user = new User()
            {
                UserName = postUserViewModel.UserName,
                UserPassword = postUserViewModel.UserPassword,
                Email = postUserViewModel.Email,
                CreateTime = DateTime.Now,
                QQNum = postUserViewModel.QQNum,
                RealName = postUserViewModel.RealName,
                Gender = postUserViewModel.Gender,
                Telephone = postUserViewModel.Telephone,
                Address = postUserViewModel.Address,
                PostCode = postUserViewModel.PostCode,
                Birthday = postUserViewModel.Birthday,
                IsDel = postUserViewModel.IsDel
            };

            OpContext.Service.User.Add(user);
            try
            {
                if (await OpContext.Service.SaveChangesAsync() < 1)
                {
                    return OpContext.JsonMsgErr(DATA_SAVECHANGES_ERROR);
                }
            }
            catch (Exception ex)
            {
                return OpContext.JsonMsgErr(ex.Message);
            }

            return OpContext.JsonMsgOK(DATA_ADD_SUCCESS);
        }

        /// <summary>
        /// PUT: Admin/User/PutUser
        /// 更新User模型
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut]
        [AjaxRequest]
        public async Task<ActionResult> PutUser([Bind(Exclude = "Action")]User user)
        {
            var userFromDb = await OpContext.Service.User.Where(u => u.Id == user.Id)
                .FirstOrDefaultAsync();
            if (userFromDb == null)
            {
                return JsonMsgFail(DATA_NOEXIST_ERROR);
            }

            if (userFromDb.UserName == "admin" || user.UserName == "admin")
            {
                return JsonMsgFail(ADMIN_NOTALLOWMODIFY_ERROR);
            }

            Tools.SetValues(userFromDb,user,ModelState.Keys.ToArray());
            try
            {
                if (await OpContext.Service.SaveChangesAsync() < 1)
                {
                    return OpContext.JsonMsgErr(DATA_SAVECHANGES_ERROR);
                }
            }
            catch (Exception ex)
            {
                return OpContext.JsonMsgErr(ex.Message);
            }

            return JsonMsgOK(DATA_MODIFY_SUCCESS);
        }

        /// <summary>
        /// ANY: Admin/User/GetUserPage
        /// 获取用户列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <returns></returns>
        [AjaxRequest]
        public async Task<ActionResult> GetUserPage(int page = 1, int rows = int.MaxValue)
        {
            var pageData = new PageData() { PageIndex = page, PageSize = rows };
            var pageList = await (await OpContext.Service.User.WherePageAsync(pageData, u => true, u => u.CreateTime))
                .Select(u => new { u.Id, u.UserName, u.Email, u.QQNum, u.RealName, u.Telephone, u.CreateTime, u.LastLoginTime, u.IsDel }).ToListAsync();

            return OpContext.JsonMsgOK(data: new { total = pageData.RowCount, rows = pageList });
        }
    }
}